package com.diaohaiwen.basic.gateway.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.diaohaiwen.common.obj.Result;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

import static com.diaohaiwen.common.enums.StatusCodeEnum.AUTH;

/**
 * @author 刁海文
 * @since 2022/4/8 10:36
 */
@Configuration
@ConfigurationProperties(prefix = "setting.static")
public class SaTokenConfigure {

    List<String> url;

    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")
                // 开放地址
                .setExcludeList(url)
//                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    if (isSwagger()) {
                        return;
                    }
                    // 拦截所有路由
                    SaRouter.match("/**").check(StpUtil::checkLogin);

                    // 权限认证 -- 不同模块, 校验不同权限
//                    SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
//                    SaRouter.match("/admin/**", r -> StpUtil.checkRole("admin"));
                    //.....
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> Result.fail(AUTH.status, e.getMessage()));
    }

    public boolean isSwagger() {
        final SaRequest request = SaHolder.getRequest();
        String uri = request.getUrl();
        return uri.contains("swagger")
                || uri.contains("/csrf")
                || uri.contains("/favicon.ico")
                || uri.contains("/webjars/")
                || uri.contains("/v3/api-docs")
                || uri.contains("/v3/Error-ModelName");
    }

    public SaTokenConfigure setUrl(List<String> url) {
        this.url = url;
        return this;
    }
}
